package com.avic.rong.fragment.collect;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.R;
import com.avic.rong.activity.mine.CollectionActivity;
import com.avic.rong.adapter.collect.GoodsAdapter;
import com.avic.rong.api.collect.DeleteCollectApi;
import com.avic.rong.api.collect.GoodsCollectApi;
import com.avic.rong.bean.collect.GoodsCollectBean;
import com.avic.rong.fragment.BaseLazyFragment;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class GoodsFragment extends BaseLazyFragment implements OnRefreshLoadMoreListener{


    @BindView(R.id.recv_shop)
    RecyclerView recv_shop;
    @BindView(R.id.srl_shop)
    SmartRefreshLayout srl_shop;
    @BindView(R.id.tv_wushujv)
    TextView tvWuShujv;

    private View view;
    private Unbinder unbinder;
    private int limit = 10;
    private int offset = 1;


    private ArrayList<GoodsCollectBean> mList;
    private GoodsAdapter shopAdapter;
    private String logintoken;
    private int newOffset;//最新页数
    private boolean isRefresh;
    private GoodsCollectApi shopCollectApi;
    private LoadingLayout loading_layout;

    //测式用的 token w4/b+EQcZZnFlmpDOn6EJH49BIWDoQfvty5QOPgq/+YLF2xTVRyFnfxTic0l1spU1DKp8PMVM1YSixxW8qPiUHQ9CAb6QSHI

   // public static String token = "w4/b+EQcZZnFlmpDOn6EJH49BIWDoQfvty5QOPgq/+YLF2xTVRyFnfxTic0l1spU1DKp8PMVM1YSixxW8qPiUHQ9CAb6QSHI";

    public GoodsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (SharedPreferencesUtil.isLogin()) {
            logintoken = SharedPreferencesUtil.getLoginToken();
        }
    }

    private String title;
    private Context mContext;

    private int mPosition;

    public static GoodsFragment getInstance(String title, Context mContext) {
        GoodsFragment shopFragment = new GoodsFragment();
        shopFragment.title = title;
        shopFragment.mContext = mContext;
        return shopFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_shop, container, false);

        loading_layout = inflate.findViewById(R.id.loading_layout);
        loading_layout.setStatus(LoadingLayout.LOADING);

        unbinder = ButterKnife.bind(this, inflate);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recv_shop.setLayoutManager(linearLayoutManager);

        mList = new ArrayList<>();

        shopAdapter = new GoodsAdapter(getActivity(), mList);
        recv_shop.setAdapter(shopAdapter);


       loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(shopCollectApi);
                loading_layout.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });
        shopAdapter.setButtonClick(new GoodsAdapter.ButtonClick() {
            @Override
            public void onClick(GoodsCollectBean collectBean, int position) {
                mPosition = position;
                DeleteCollectApi deleteCollectApi = new DeleteCollectApi((CollectionActivity) mContext, deleteCollectListener);
                deleteCollectApi.setArgument(logintoken, collectBean.getFavoritesFlag(), collectBean.getTargetId());
                HttpManager.getInstance().doHttpDeal(deleteCollectApi);
            }
        });

        srl_shop.setOnRefreshLoadMoreListener(this);

        return inflate;
    }

    //取消收藏
    HttpOnNextListener<BaseResultEntity> deleteCollectListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                mList.remove(mPosition);
                ToastTools.showPublicToast("取消收藏成功");
                shopAdapter.notifyDataSetChanged();
            } else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    };

    private void initData() {
        shopCollectApi = new GoodsCollectApi((CollectionActivity) getActivity(), shopCollectListener);
        shopCollectApi.setArgument(logintoken, offset, limit);
//        shopCollectApi.setCancel(false);
//        shopCollectApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(shopCollectApi);

    }

    HttpOnNextListener<BaseResultEntity> shopCollectListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override

        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                List<GoodsCollectBean> data = (List<GoodsCollectBean>) baseResultEntity.getData();
                Log.e("GoodsFragment", "onNext: " + data.toString());
                loading_layout.setStatus(LoadingLayout.SUCCESS);
                if (data != null) {
                    if (isRefresh){
                        mList.clear();
                    }
                    mList.addAll(data);
                    shopAdapter.notifyDataSetChanged();


                    if (mList!=null&&mList.size()<=0){
                        loading_layout.setStatus(LoadingLayout.EMPTY);
                        loading_layout.setEmptyImageVisible(true);
                        loading_layout.setEmptyText("您还未添加过收藏哦~");
                        loading_layout.setEmptyImage(R.mipmap.collection_mpty);
                    }
                    if (srl_shop!=null) {
                        if (isRefresh) {
                            srl_shop.finishRefresh();
                        } else {
                            srl_shop.finishLoadMore();
                        }
                    }
                }
            } else{
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        offset = offset + 1;
        shopCollectApi.setOffset(offset);
        HttpManager.getInstance().doHttpDeal(shopCollectApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        offset = 1;
        shopCollectApi.setOffset(offset);
        HttpManager.getInstance().doHttpDeal(shopCollectApi);
    }

    @Override
    public void loadData() {

        initData();
    }
}
